package com.yy.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    static{
        try {
            //解析文件、初始化连接池等等这些工作都非常耗时。
            InputStream inputStream = Resources.getResourceAsStream("mybatis.cfg.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){

        //同一个线程获取同一个session
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession ==null) {
            sqlSession = sqlSessionFactory.openSession(true);
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }


}

